<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { marked } from 'marked'
import { apiClient } from '@/utils/api'
import Prism from 'prismjs'
import 'prismjs/themes/prism-tomorrow.css'
import 'prismjs/components/prism-javascript'
import 'prismjs/components/prism-typescript'
import 'prismjs/components/prism-css'
import 'prismjs/components/prism-json'
import 'prismjs/components/prism-python'
import 'prismjs/components/prism-java'
import 'prismjs/components/prism-bash'
import 'prismjs/components/prism-markdown'

// 消息接口类型定义
interface Message {
  id: string
  content: string
  role: 'user' | 'assistant'
  timestamp: Date | string
  isLoading?: boolean
}

// AI配置接口类型定义
interface AiConfig {
  id?: string
  name: string
  provider: string
  model: string
  apiUrl: string
  apiKey: string
  description?: string
  parameters: {
    temperature: number
    maxTokens: number
    topP?: number
  }
  isDefault?: boolean
  isActive?: boolean
  createdAt?: string | Date
  updatedAt?: string | Date
}

const authStore = useAuthStore()

// 聊天相关状态
const messages = ref<Message[]>([])
const currentMessage = ref('')
const isLoading = ref(false)
const chatContainer = ref<HTMLElement>()

// 历史对话记录
const chatHistory = ref<Array<{
  id: string
  title: string
  timestamp: Date
  messages: Message[]
  sessionId?: string // 数据库会话ID
}>>([])

const currentChatId = ref('')
const currentSessionId = ref<string | null>(null) // 当前数据库会话ID

// 搜索和筛选相关状态
const searchQuery = ref('')
const selectedChatType = ref('')

// AI配置相关状态
const aiConfigs = ref<AiConfig[]>([])
const currentAiConfig = ref<AiConfig | null>(null)
const selectedConfigId = ref<string | null>(null)
const isLoadingConfig = ref(false)

// 计算属性
const isAdmin = computed(() => authStore.user?.role === 'admin')
const currentChat = computed(() =>
  chatHistory.value.find(chat => chat.id === currentChatId.value)
)

// 根据selectedConfigId获取当前选中的AI配置
const selectedAiConfig = computed(() => {
  if (selectedConfigId.value) {
    return aiConfigs.value.find(config => config.id === selectedConfigId.value)
  }
  return null
})

// 筛选后的对话历史
const filteredChatHistory = computed(() => {
  let filtered = chatHistory.value

  // 按搜索关键词筛选
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase().trim()
    filtered = filtered.filter(chat =>
      chat.title.toLowerCase().includes(query) ||
      chat.messages.some(msg => msg.content.toLowerCase().includes(query))
    )
  }

  // 按会话类型筛选
  if (selectedChatType.value) {
    if (selectedChatType.value === 'local') {
      filtered = filtered.filter(chat => !chat.sessionId)
    } else if (selectedChatType.value === 'database') {
      filtered = filtered.filter(chat => chat.sessionId)
    }
  }

  return filtered
})

// 加载AI配置列表
const loadAiConfigs = async () => {
  if (!authStore.isAuthenticated) {
    return
  }

  try {
    isLoadingConfig.value = true
    const response = await apiClient.get('/ai-config')
    // 后端返回格式: {success: true, data: {configs: [...], total: ...}}
    aiConfigs.value = response.data.data?.configs || []

    // 自动选择isDefault为true的配置作为默认值
    const defaultConfig = aiConfigs.value.find(config => config.isDefault)
    if (defaultConfig && !selectedConfigId.value) {
      selectedConfigId.value = defaultConfig.id || null
    }
  } catch (error) {
    console.error('加载AI配置失败:', error)
  } finally {
    isLoadingConfig.value = false
  }
}

// 加载默认AI配置
const loadDefaultConfig = async () => {
  try {
    const response = await apiClient.get('/ai-config/default/config')
    currentAiConfig.value = response.data.data.config
  } catch (error: any) {
    console.error('加载默认配置失败:', error.response?.data?.error?.message || error.message)
    // 如果没有默认配置，使用本地存储的配置作为后备
    currentAiConfig.value = {
      name: '默认配置',
      provider: 'siliconflow',
      apiKey: localStorage.getItem('kb_api_key') || '',
      apiUrl: localStorage.getItem('kb_base_url') || 'https://api.siliconflow.cn/v1',
      model: localStorage.getItem('kb_model') || 'deepseek-ai/DeepSeek-V2.5',
      parameters: {
        temperature: 0.7,
        maxTokens: 8000 // 增加到8000以支持更长的回答
      }
    }
  }
}

// 创建新的数据库会话
const createDatabaseSession = async (title?: string) => {
  if (!authStore.isAuthenticated) {
    return null // 未登录用户不创建数据库会话
  }

  try {
    // 使用用户选择的AI配置，如果没有选择则使用默认配置
    const aiConfigToUse = selectedAiConfig.value || currentAiConfig.value

    const response = await apiClient.post('/chat/sessions', {
      title: title || '新对话',
      aiConfigId: aiConfigToUse?.id
    })
    return response.data.data.session
  } catch (error) {
    console.error('创建数据库会话失败:', error)
    return null
  }
}

// 发送消息到数据库
const sendMessageToDatabase = async (sessionId: string, content: string, role: 'user' | 'assistant') => {
  if (!authStore.isAuthenticated || !sessionId) {
    return null
  }

  try {
    const response = await apiClient.post(`/chat/sessions/${sessionId}/messages`, {
      content,
      role,
      aiConfigId: currentAiConfig.value?.id || null
    })
    return response.data.data
  } catch (error) {
    console.error('发送消息到数据库失败:', error)
    return null
  }
}

// 前端开发相关关键词库
const frontendKeywords = [
  'vue', 'react', 'angular', 'javascript', 'typescript', 'html', 'css', 'scss', 'sass',
  'node', 'npm', 'yarn', 'webpack', 'vite', 'rollup', 'babel', 'eslint', 'prettier',
  'axios', 'fetch', 'ajax', 'api', 'rest', 'graphql', 'json', 'xml',
  'component', 'props', 'state', 'hook', 'lifecycle', 'router', 'store', 'vuex', 'pinia',
  'redux', 'mobx', 'context', 'provider', 'ref', 'reactive', 'computed', 'watch',
  'dom', 'event', 'click', 'submit', 'form', 'input', 'button', 'div', 'span',
  'flex', 'grid', 'layout', 'responsive', 'mobile', 'desktop', 'media', 'query',
  'animation', 'transition', 'transform', 'keyframe', 'hover', 'focus', 'active',
  'performance', 'optimization', 'bundle', 'lazy', 'async', 'await', 'promise',
  'test', 'jest', 'cypress', 'vitest', 'unit', 'e2e', 'mock', 'debug',
  '前端', '组件', '页面', '接口', '样式', '布局', '响应式', '性能', '优化', '测试'
]

// 非前端相关关键词库
const nonFrontendKeywords = [
  '历史', '政治', '娱乐', '明星', '电影', '音乐', '体育', '足球', '篮球',
  '后端', 'java', 'python', 'php', 'c++', 'c#', 'go', 'rust', 'ruby',
  'mysql', 'postgresql', 'mongodb', 'redis', 'docker', 'kubernetes',
  '数据库', '服务器', '运维', '网络', '安全', '算法', '数据结构',
  '做饭', '旅游', '购物', '健康', '医疗', '法律', '金融', '股票',
  'history', 'politics', 'entertainment', 'celebrity', 'movie', 'music', 'sports',
  'backend', 'database', 'server', 'devops', 'network', 'security', 'algorithm'
]

// 验证问题是否属于前端开发范围
const validateQuestionScope = (question: string): { isValid: boolean; reason?: string } => {
  const lowerQuestion = question.toLowerCase()
  
  // 检查是否包含非前端关键词
  const hasNonFrontendKeywords = nonFrontendKeywords.some(keyword => 
    lowerQuestion.includes(keyword.toLowerCase())
  )
  
  if (hasNonFrontendKeywords) {
    return { 
      isValid: false, 
      reason: '检测到非前端开发相关内容' 
    }
  }
  
  // 检查是否包含前端关键词
  const hasFrontendKeywords = frontendKeywords.some(keyword => 
    lowerQuestion.includes(keyword.toLowerCase())
  )
  
  // 如果问题很短（少于10个字符）且没有前端关键词，可能是闲聊
  if (question.trim().length < 10 && !hasFrontendKeywords) {
    return { 
      isValid: false, 
      reason: '问题过于简短且未包含前端技术相关内容' 
    }
  }
  
  // 检查是否是明显的非技术问题
  const casualPhrases = ['你好', 'hello', '怎么样', '今天', '天气', '吃饭', '睡觉', '再见', 'bye']
  const isCasualChat = casualPhrases.some(phrase => 
    lowerQuestion.includes(phrase) && !hasFrontendKeywords
  )
  
  if (isCasualChat) {
    return { 
      isValid: false, 
      reason: '检测到日常闲聊内容' 
    }
  }
  
  return { isValid: true }
}

// 发送消息
const sendMessage = async () => {
  if (!currentMessage.value.trim() || isLoading.value) return

  const messageContent = currentMessage.value
  currentMessage.value = ''
  
  // 前端范围验证
  const validation = validateQuestionScope(messageContent)
  if (!validation.isValid) {
    const rejectionMessage = {
      id: Date.now().toString(),
      content: messageContent,
      role: 'user' as const,
      timestamp: new Date()
    }
    
    const assistantRejection = {
      id: (Date.now() + 1).toString(),
      content: `抱歉，我只能回答前端开发相关的问题。请询问关于Vue.js、React、JavaScript、CSS等前端技术的问题。\n\n检测原因：${validation.reason}`,
      role: 'assistant' as const,
      timestamp: new Date()
    }
    
    messages.value.push(rejectionMessage, assistantRejection)
    
    // 保存到数据库（如果用户已登录）
    if (currentSessionId.value && authStore.isAuthenticated) {
      try {
        await sendMessageToDatabase(currentSessionId.value, messageContent, 'user')
        await sendMessageToDatabase(currentSessionId.value, assistantRejection.content, 'assistant')
      } catch (error) {
        console.warn('保存拒绝消息到数据库失败:', error)
      }
    }
    
    await nextTick()
    scrollToBottom()
    updateCurrentChat()
    return
  }

  // 如果没有当前会话，先创建一个
  if (!currentSessionId.value && authStore.isAuthenticated) {
    const session = await createDatabaseSession()
    if (session) {
      currentSessionId.value = session.id
      // 更新当前聊天记录的sessionId
      const currentChat = chatHistory.value.find(chat => chat.id === currentChatId.value)
      if (currentChat) {
        currentChat.sessionId = session.id
      }
    }
  }

  const userMessage = {
    id: Date.now().toString(),
    content: messageContent,
    role: 'user' as const,
    timestamp: new Date()
  }

  messages.value.push(userMessage)

  // 添加加载中的助手消息
  const loadingMessage = {
    id: (Date.now() + 1).toString(),
    content: '',
    role: 'assistant' as const,
    timestamp: new Date(),
    isLoading: true
  }
  messages.value.push(loadingMessage)

  isLoading.value = true

  try {
    await nextTick()
    scrollToBottom()

    // 使用用户选择的AI配置，如果没有选择则使用默认配置
    const aiConfigToUse = selectedAiConfig.value || currentAiConfig.value

    if (!aiConfigToUse || !aiConfigToUse.apiKey) {
      throw new Error('请先选择AI模型或配置API密钥')
    }

    // 调用后端AI接口
    // 只发送当前用户消息，不发送历史对话
    const requestPayload = {
      messages: [
        {
          role: 'system',
          content: '你是一个专业的前端开发助手。重要规则：你只能回答与前端开发相关的问题，包括：Vue.js、React、Angular、JavaScript、TypeScript、HTML、CSS、前端工具链、前端性能优化、前端测试、Node.js、npm、webpack、vite等。\n\n如果用户询问的问题与前端开发无关（如历史、政治、娱乐、其他技术领域等），你必须拒绝回答，并回复："抱歉，我只能回答前端开发相关的问题。请询问关于Vue.js、React、JavaScript、CSS等前端技术的问题。"\n\n严格遵守此规则，不要回答任何非前端开发的问题。'
        },
        {
          role: 'user',
          content: messageContent
        }
      ],
      model: aiConfigToUse.model || 'deepseek-chat',
      temperature: aiConfigToUse.parameters?.temperature || 0.7,
      max_tokens: aiConfigToUse.parameters?.maxTokens || 8000,
      apiKey: aiConfigToUse.apiKey,
      apiUrl: aiConfigToUse.apiUrl // 使用apiUrl字段
    }
    
    console.log('=== 发送按钮诊断信息 ===')
    console.log('发送的完整请求内容:', JSON.stringify(requestPayload, null, 2))
    console.log('当前AI配置:', aiConfigToUse)
    console.log('当前用户消息:', messageContent)
    console.log('apiClient baseURL:', apiClient.defaults.baseURL)
    console.log('完整请求URL:', apiClient.defaults.baseURL + '/ai/chat')
    console.log('========================')

    // 为AI请求设置更长的超时时间（3分钟）
    const response = await apiClient.post('/ai/chat', requestPayload, {
      timeout: 420000 // 7分钟超时
    })

    const assistantMessage = response.data.data?.message || '抱歉，我无法回答这个问题。'

    // 更新加载中的消息
    const loadingIndex = messages.value.findIndex(msg => msg.isLoading)
    if (loadingIndex !== -1) {
      messages.value[loadingIndex] = {
        ...loadingMessage,
        content: assistantMessage,
        isLoading: false
      }
    }

    // 保存用户消息和助手回复到数据库（如果用户已登录）
    if (currentSessionId.value && authStore.isAuthenticated) {
      try {
        await sendMessageToDatabase(currentSessionId.value, messageContent, 'user')
        await sendMessageToDatabase(currentSessionId.value, assistantMessage, 'assistant')
      } catch (error) {
        console.warn('保存消息到数据库失败:', error)
      }
    }

  } catch (error) {
    console.error('发送消息失败:', error)
    // 更新加载中的消息为错误消息
    const loadingIndex = messages.value.findIndex(msg => msg.isLoading)
    if (loadingIndex !== -1) {
      const errorMessage = `抱歉，发生了错误: ${error instanceof Error ? error.message : '未知错误'}`
      messages.value[loadingIndex] = {
        ...loadingMessage,
        content: errorMessage,
        isLoading: false
      }

      // 发送错误消息到数据库
      if (currentSessionId.value) {
        await sendMessageToDatabase(currentSessionId.value, errorMessage, 'assistant')
      }
    }
  } finally {
    isLoading.value = false
    await nextTick()
    scrollToBottom()
    updateCurrentChat()
  }
}

// 加载用户的数据库会话列表
const loadDatabaseSessions = async () => {
  if (!authStore.isAuthenticated) {
    return []
  }

  try {
    const response = await apiClient.get('/chat/sessions')
    return response.data.data.sessions || []
  } catch (error) {
    console.error('加载数据库会话失败:', error)
    return []
  }
}

// 加载特定会话的消息历史
const loadSessionMessages = async (sessionId: string) => {
  if (!authStore.isAuthenticated || !sessionId) {
    return []
  }

  try {
    const response = await apiClient.get(`/chat/sessions/${sessionId}/messages`)
    return response.data.data.data || []
  } catch (error) {
    console.error('加载会话消息失败:', error)
    return []
  }
}

// 从数据库会话创建聊天历史项
const createChatFromSession = (session: any) => {
  return {
    id: `session-${session.id}`,
    sessionId: session.id,
    title: session.title || '新对话',
    messages: [],
    timestamp: new Date(session.createdAt),
    aiConfig: session.aiConfigId ? aiConfigs.value.find(config => config.id === session.aiConfigId) : null
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 创建新对话
const createNewChat = () => {
  const newChat = {
    id: Date.now().toString(),
    sessionId: undefined, // 数据库会话ID，将在发送第一条消息时创建
    title: `对话 ${chatHistory.value.length + 1}`,
    timestamp: new Date(),
    messages: [{
      id: '1',
      content: '您好！我是前端知识库助手，可以帮助您解答前端开发相关的问题。请问有什么可以帮助您的吗？',
      role: 'assistant' as const,
      timestamp: new Date()
    }]
  }

  chatHistory.value.push(newChat)
  currentSessionId.value = null
  switchChat(newChat.id)
  saveChatHistory()
}

// 切换对话
const switchChat = async (chatId: string) => {
  updateCurrentChat()
  currentChatId.value = chatId
  const chat = chatHistory.value.find(c => c.id === chatId)
  if (chat) {
    currentSessionId.value = chat.sessionId ?? null

    // 如果是数据库会话，从数据库加载消息
    if (chat.sessionId && authStore.isAuthenticated) {
      try {
        const dbMessages = await loadSessionMessages(chat.sessionId)
        // 转换数据库消息格式
        const convertedMessages = dbMessages.map((msg: any) => ({
          id: msg.id.toString(),
          content: msg.content,
          role: msg.role,
          timestamp: new Date(msg.createdAt)
        }))
        // 按时间戳升序排序，确保消息按正确的时间顺序显示
        convertedMessages.sort((a: any, b: any) => a.timestamp.getTime() - b.timestamp.getTime())
        messages.value = convertedMessages
        chat.messages = convertedMessages // 更新本地缓存
      } catch (error) {
        console.error('加载会话消息失败:', error)
        messages.value = [...chat.messages] // 使用本地缓存
      }
    } else {
      messages.value = [...chat.messages]
    }

    nextTick(() => scrollToBottom())
  }
}

// 更新数据库会话标题
const updateDatabaseSessionTitle = async (sessionId: string, title: string) => {
  if (!authStore.isAuthenticated || !sessionId) {
    return false
  }

  try {
    await apiClient.put(`/chat/sessions/${sessionId}`, { title })
    return true
  } catch (error) {
    console.error('更新数据库会话标题失败:', error)
    return false
  }
}

// 重命名聊天
const renameChat = async (chatId: string) => {
  const chat = chatHistory.value.find(c => c.id === chatId)
  if (!chat) return

  const newTitle = prompt('请输入新的对话标题:', chat.title)
  if (!newTitle || newTitle.trim() === '' || newTitle === chat.title) {
    return
  }

  // 如果是数据库会话，更新数据库
  if (chat.sessionId) {
    const success = await updateDatabaseSessionTitle(chat.sessionId, newTitle.trim())
    if (!success) {
      alert('更新数据库会话标题失败')
      return
    }
  }

  // 更新本地标题
  chat.title = newTitle.trim()
  saveChatHistory()
}

// 更新当前对话
const updateCurrentChat = () => {
  const chatIndex = chatHistory.value.findIndex(chat => chat.id === currentChatId.value)
  if (chatIndex !== -1) {
    chatHistory.value[chatIndex].messages = [...messages.value]
    // 更新标题为第一条用户消息的前20个字符
    const firstUserMessage = messages.value.find(msg => msg.role === 'user')
    if (firstUserMessage && chatHistory.value[chatIndex].title.startsWith('对话')) {
      chatHistory.value[chatIndex].title = firstUserMessage.content.slice(0, 20) + (firstUserMessage.content.length > 20 ? '...' : '')
    }
    // 保存聊天历史
    saveChatHistory()
  }
}

// 删除数据库会话
const deleteDatabaseSession = async (sessionId: string) => {
  if (!authStore.isAuthenticated || !sessionId) {
    return false
  }

  try {
    await apiClient.delete(`/chat/sessions/${sessionId}`)
    return true
  } catch (error) {
    console.error('删除数据库会话失败:', error)
    return false
  }
}

// 删除对话
const deleteChat = async (chatId: string) => {
  if (chatHistory.value.length <= 1) return

  const chat = chatHistory.value.find(c => c.id === chatId)
  if (!chat) return

  // 如果是数据库会话，先删除数据库记录
  if (chat.sessionId) {
    const success = await deleteDatabaseSession(chat.sessionId)
    if (!success) {
      // 删除失败，询问用户是否只删除本地记录
      const confirmDelete = confirm('删除数据库会话失败，是否只删除本地记录？')
      if (!confirmDelete) {
        return
      }
    }
  }

  const index = chatHistory.value.findIndex(chat => chat.id === chatId)
  if (index !== -1) {
    chatHistory.value.splice(index, 1)
    if (currentChatId.value === chatId) {
      await switchChat(chatHistory.value[0].id)
    }
    saveChatHistory()
  }
}

// 清空当前对话
const clearCurrentChat = () => {
  messages.value = [{
    id: '1',
    content: '您好！我是前端知识库助手，可以帮助您解答前端开发相关的问题。请问有什么可以帮助您的吗？',
    role: 'assistant',
    timestamp: new Date()
  }]
  updateCurrentChat()
}

// 渲染Markdown
const renderMarkdown = (content: string) => {
  // 创建自定义renderer
  const renderer = new marked.Renderer()
  
  // 自定义代码块渲染
  renderer.code = function(code: any, lang: any) {
    // 使用Prism.js进行代码高亮
    if (lang && Prism.languages[lang]) {
      try {
        const highlighted = Prism.highlight(code, Prism.languages[lang], lang)
        return `<div class="code-block-wrapper">
          <div class="code-block-header">
            <span class="code-language">${lang}</span>
            <button class="copy-code-btn" onclick="copyCode(this)" title="复制代码">
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
                <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
              </svg>
            </button>
          </div>
          <pre class="language-${lang}"><code class="language-${lang}">${highlighted}</code></pre>
        </div>`
      } catch (e) {
        console.warn('代码高亮失败:', e)
        return `<pre class="language-${lang}"><code class="language-${lang}">${escapeHtml(code)}</code></pre>`
      }
    }
    // 如果没有语言标识或不支持该语言，使用普通格式
    return `<div class="code-block-wrapper">
      <div class="code-block-header">
        <span class="code-language">text</span>
        <button class="copy-code-btn" onclick="copyCode(this)" title="复制代码">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
            <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
            <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
          </svg>
        </button>
      </div>
      <pre><code>${escapeHtml(code)}</code></pre>
    </div>`
  }
  
  // 配置marked选项
  marked.setOptions({
    renderer: renderer,
    breaks: true, // 支持换行
    gfm: true, // 启用GitHub风格的markdown
    sanitize: false, // 允许HTML（注意：在生产环境中要谨慎使用）
    smartLists: true,
    smartypants: true
  })
  
  const html = marked(content)
  
  // 在下一个tick中高亮所有代码块
  nextTick(() => {
    Prism.highlightAll()
  })
  
  return html
}

// HTML转义函数
const escapeHtml = (unsafe: string) => {
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;")
}

// 复制代码功能
const copyCode = (button: HTMLElement) => {
  const codeBlock = button.closest('.code-block-wrapper')?.querySelector('code')
  if (codeBlock) {
    const text = codeBlock.textContent || ''
    navigator.clipboard.writeText(text).then(() => {
      // 显示复制成功提示
      const originalText = button.innerHTML
      button.innerHTML = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
        <polyline points="20,6 9,17 4,12"></polyline>
      </svg>`
      button.style.color = '#10b981'
      
      setTimeout(() => {
        button.innerHTML = originalText
        button.style.color = ''
      }, 2000)
    }).catch(err => {
      console.error('复制失败:', err)
    })
  }
}

// 将复制函数挂载到全局，以便在HTML中调用
;(window as any).copyCode = copyCode

// 加载聊天历史
const loadChatHistory = async () => {
  try {
    // 如果用户已认证，优先从数据库加载
    if (authStore.isAuthenticated) {
      await loadChatHistoryFromDatabase()
    } else {
      // 未认证用户从本地存储加载
      loadChatHistoryFromLocal()
    }
  } catch (error) {
    console.error('加载聊天历史失败:', error)
    // 如果加载失败，尝试从本地存储加载
    loadChatHistoryFromLocal()
  }
}

// 从数据库加载聊天历史
const loadChatHistoryFromDatabase = async () => {
  try {
    // 获取用户的会话列表
    const sessionsResponse = await apiClient.get('/chat/sessions')
    const sessions = sessionsResponse.data.data.data || []

    // 确保sessions是数组
    if (!Array.isArray(sessions)) {
      return
    }

    // 为每个会话加载消息历史
    const chatHistoryData = []
    for (const session of sessions) {
      try {
        const messagesResponse = await apiClient.get(`/chat/sessions/${session.id}/messages`)
        const messages = messagesResponse.data.data.data || []
        // 转换为前端格式
        const convertedMessages = messages.map((msg: any) => ({
          id: msg.id.toString(),
          content: msg.content,
          role: msg.role,
          timestamp: new Date(msg.createdAt)
        }))

        chatHistoryData.push({
          id: `session-${session.id}`,
          sessionId: session.id,
          title: session.title || '新对话',
          timestamp: new Date(session.createdAt),
          messages: convertedMessages
        })
      } catch (error) {
        console.error(`加载会话 ${session.id} 的消息失败:`, error)
        // 即使某个会话的消息加载失败，也要保留会话记录
        chatHistoryData.push({
          id: `session-${session.id}`,
          sessionId: session.id,
          title: session.title || '新对话',
          timestamp: new Date(session.createdAt),
          messages: []
        })
      }
    }

    // 按时间倒序排列（最新的在前面）
    chatHistory.value = chatHistoryData.sort((a, b) =>
      new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
    )

    // 如果有会话，切换到最新的会话
    if (chatHistory.value.length > 0) {
      await switchChat(chatHistory.value[0].id)
    }

  } catch (error) {
    console.error('从数据库加载聊天历史失败:', error)
    throw error
  }
}

// 从本地存储加载聊天历史
const loadChatHistoryFromLocal = () => {
  try {
    const savedHistory = localStorage.getItem('kb_chat_history')
    if (savedHistory) {
      const parsedHistory = JSON.parse(savedHistory)
      if (Array.isArray(parsedHistory) && parsedHistory.length > 0) {
        // 恢复时间戳对象
        chatHistory.value = parsedHistory.map(chat => ({
          ...chat,
          timestamp: new Date(chat.timestamp),
          messages: chat.messages.map((msg: Message) => ({
            ...msg,
            timestamp: new Date(msg.timestamp)
          }))
        }))

        // 恢复当前对话
        const savedCurrentChatId = localStorage.getItem('kb_current_chat_id')
        if (savedCurrentChatId && chatHistory.value.find(chat => chat.id === savedCurrentChatId)) {
          switchChat(savedCurrentChatId)
        } else if (chatHistory.value.length > 0) {
          switchChat(chatHistory.value[0].id)
        }
      }
    }
  } catch (error) {
    console.error('从本地存储加载聊天历史失败:', error)
  }
}

// 保存聊天历史
const saveChatHistory = () => {
  try {
    localStorage.setItem('kb_chat_history', JSON.stringify(chatHistory.value))
    localStorage.setItem('kb_current_chat_id', currentChatId.value)
  } catch (error) {
    console.error('保存聊天历史失败:', error)
  }
}

// 处理回车发送
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

// 格式化时间显示
const formatTime = (timestamp: Date | string): string => {
  const date = timestamp instanceof Date ? timestamp : new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 初始化数据库会话历史
const initializeDatabaseSessions = async () => {
  if (!authStore.isAuthenticated) {
    return
  }

  try {
    const sessions = await loadDatabaseSessions()

    // 将数据库会话转换为聊天历史格式并合并
    const sessionChats = sessions.map(createChatFromSession)

    // 合并本地聊天历史和数据库会话，去重
    const existingSessionIds = new Set(chatHistory.value.map(chat => chat.sessionId).filter(Boolean))
    const newSessionChats = sessionChats.filter((chat: { id: string; title: string; timestamp: Date; messages: Message[]; sessionId?: string }) => !existingSessionIds.has(chat.sessionId))

    if (newSessionChats.length > 0) {
      chatHistory.value = [...newSessionChats, ...chatHistory.value]
      saveChatHistory()
    }
  } catch (error) {
    console.error('初始化数据库会话失败:', error)
  }
}

// 组件挂载时初始化
onMounted(async () => {
  // 恢复认证状态
  authStore.restoreAuth()

  // 等待下一个tick确保认证状态完全恢复
  await nextTick()

  await loadChatHistory()

  // 总是加载默认配置（不需要认证）
  await loadDefaultConfig()

  // 检查是否已认证再调用需要认证的API
  if (authStore.isAuthenticated) {
    await loadAiConfigs()
  } else {
    console.warn('用户未认证,跳过加载AI配置列表')
  }

  // 如果没有聊天历史，创建一个新的
  if (chatHistory.value.length === 0) {
    createNewChat()
  }

  nextTick(() => scrollToBottom())
})

// 监听登录状态变化
watch(() => authStore.isAuthenticated, async (isAuthenticated) => {
  if (isAuthenticated) {
    // 用户登录后，重新加载聊天历史（从数据库）
    await loadChatHistory()
  } else {
    // 用户登出后，清除数据库会话相关的聊天历史
    chatHistory.value = chatHistory.value.filter(chat => !chat.sessionId)
    currentSessionId.value = null
    saveChatHistory()

    // 如果当前聊天是数据库会话，切换到本地聊天或创建新聊天
    const currentChat = chatHistory.value.find(chat => chat.id === currentChatId.value)
    if (!currentChat) {
      if (chatHistory.value.length > 0) {
        await switchChat(chatHistory.value[0].id)
      } else {
        createNewChat()
      }
    }
  }
})
</script>

<template>
  <div class="min-h-screen bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-screen flex">
      <!-- 侧边栏 - 对话历史 -->
      <div class="w-80 bg-white border-r border-gray-200 flex flex-col">
        <!-- 侧边栏头部 -->
        <div class="p-4 border-b border-gray-200">
          <div class="flex items-center justify-between mb-4">
            <h2 class="text-lg font-semibold text-gray-900">前端知识库</h2>
            <button @click="createNewChat"
              class="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-lg transition-colors" title="新建对话">
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
              </svg>
            </button>
          </div>

          <!-- 认证状态提示 -->
          <div v-if="!authStore.isAuthenticated" class="mb-4 p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
            <div class="flex items-center">
              <svg class="w-4 h-4 text-yellow-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z" />
              </svg>
              <span class="text-sm text-yellow-800">未登录状态，使用本地配置</span>
            </div>
            <router-link to="/login" class="text-xs text-yellow-700 hover:text-yellow-900 underline mt-1 block">
              点击登录获取完整功能
            </router-link>
          </div>

          <!-- 已登录状态提示 -->
          <div v-else class="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg">
            <div class="flex items-center">
              <svg class="w-4 h-4 text-green-600 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <span class="text-sm text-green-800">已登录，可使用完整功能</span>
            </div>
          </div>


        </div>

        <!-- 对话历史列表 -->
        <div class="flex-1 overflow-y-auto">
          <div class="p-2 space-y-1">
            <div v-for="chat in filteredChatHistory" :key="chat.id" class="group relative">
              <button @click="switchChat(chat.id)" :class="[
                'w-full text-left p-3 rounded-lg transition-colors',
                currentChatId === chat.id
                  ? 'bg-blue-50 text-blue-900 border border-blue-200'
                  : 'text-gray-700 hover:bg-gray-100'
              ]">
                <div class="flex items-center justify-between mb-1">
                  <div class="font-medium text-sm truncate flex-1">{{ chat.title }}</div>
                  <div class="flex items-center gap-1 ml-2">
                    <span v-if="chat.sessionId" class="px-1.5 py-0.5 bg-green-100 text-green-700 text-xs rounded"
                      title="数据库会话">DB</span>
                    <span v-else class="px-1.5 py-0.5 bg-gray-100 text-gray-600 text-xs rounded" title="本地会话">本地</span>
                  </div>
                </div>
                <div class="text-xs text-gray-500">{{ formatTime(chat.timestamp) }}</div>
              </button>

              <!-- 重命名按钮 -->
              <button @click="renameChat(chat.id)"
                class="absolute top-2 right-8 p-1 text-gray-400 hover:text-blue-500 opacity-0 group-hover:opacity-100 transition-opacity"
                title="重命名对话">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                </svg>
              </button>

              <!-- 删除按钮 -->
              <button v-if="chatHistory.length > 1" @click="deleteChat(chat.id)"
                class="absolute top-2 right-2 p-1 text-gray-400 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-opacity"
                :title="chat.sessionId ? '删除数据库会话' : '删除本地对话'">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                    d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 主聊天区域 -->
      <div class="flex-1 flex flex-col " style="height: calc(100vh - 64px);overflow: hidden;">
        <!-- 聊天头部 -->
        <div class="bg-white border-b border-gray-200 py-4">
          <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <!-- 页面标题 -->
            <div class="flex items-center justify-between mb-4">
              <div>
                <h3 class="text-lg font-semibold text-gray-900">{{ currentChat?.title || '前端知识库' }}</h3>
                <p class="text-sm text-gray-500">AI助手为您解答前端开发问题</p>
              </div>
            </div>

            <!-- 搜索和筛选栏 -->
            <div class="flex flex-wrap items-center gap-4 mb-4">
              <!-- 搜索框 -->
              <div class="flex-1 min-w-64">
                <div class="relative">
                  <input v-model="searchQuery" type="text" placeholder="搜索对话历史..."
                    class="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" />
                  <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                    </svg>
                  </div>
                </div>
              </div>

              <!-- 会话类型筛选 -->
              <div class="min-w-32">
                <select v-model="selectedChatType"
                  class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                  <option value="">全部会话</option>
                  <option value="local">本地会话</option>
                  <option value="database">数据库会话</option>
                </select>
              </div>

              <!-- 操作按钮 -->
              <div class="flex items-center gap-2">
                <button @click="createNewChat"
                  class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2"
                  title="新建对话">
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                  </svg>
                  新建对话
                </button>

                <button @click="clearCurrentChat"
                  class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors flex items-center gap-2"
                  title="清空当前对话">
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                  清空对话
                </button>

                <button @click="loadChatHistory"
                  class="px-4 py-2 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors flex items-center gap-2"
                  title="刷新对话历史">
                  <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                  </svg>
                  刷新
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 消息列表 -->
        <div ref="chatContainer" class="flex-1 overflow-y-auto p-4">
          <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-4">
            <div v-for="message in messages" :key="message.id" :class="[
              'flex',
              message.role === 'user' ? 'justify-end' : 'justify-start'
            ]">
              <div :class="[
                'max-w-3xl px-4 py-3 rounded-lg',
                message.role === 'user'
                  ? 'bg-blue-600 text-white'
                  : 'bg-white border border-gray-200 text-gray-900'
              ]">
                <div v-if="message.isLoading" class="flex items-center space-x-2">
                  <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-gray-600"></div>
                  <span class="text-sm">思考中...</span>
                </div>
                <div v-else-if="message.role === 'assistant'" class="prose prose-sm max-w-none"
                  v-html="renderMarkdown(message.content)"></div>
                <div v-else class="whitespace-pre-wrap">{{ message.content }}</div>
                <div class="text-xs mt-2 opacity-70">{{ formatTime(message.timestamp) }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="bg-white border-t border-gray-200 p-4">
          <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex space-x-3 items-end">
              <!-- 模型选择 -->
              <div v-if="authStore.isAuthenticated && aiConfigs.length > 0" class="flex-shrink-0">
                <label class="block text-sm font-medium text-gray-700 mb-1">选择AI模型</label>
                <select v-model="selectedConfigId"
                  @change="(event: Event) => selectedConfigId = (event.target as HTMLSelectElement).value"
                  class="w-48 border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                  <option v-for="config in aiConfigs" :key="config.id" :value="config.id">
                    {{ config.name }} ({{ config.model }})
                  </option>
                </select>
              </div>

              <!-- 输入框 -->
              <div class="flex-1 flex space-x-3">
                <textarea v-model="currentMessage" @keydown="handleKeydown"
                  placeholder="输入您的问题... (Shift+Enter换行，Enter发送)"
                  class="flex-1 resize-none border border-gray-300 rounded-lg px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                  rows="2" :disabled="isLoading"></textarea>
                <button @click="sendMessage" :disabled="!currentMessage.trim() || isLoading"
                  class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors">
                  发送
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.prose {
  color: inherit;
  line-height: 1.6;
}

.prose h1,
.prose h2,
.prose h3,
.prose h4,
.prose h5,
.prose h6 {
  color: inherit;
  margin-top: 1.5em;
  margin-bottom: 0.75em;
  font-weight: 600;
  line-height: 1.25;
}

.prose h1 {
  font-size: 1.5em;
  border-bottom: 2px solid #e5e7eb;
  padding-bottom: 0.5em;
}

.prose h2 {
  font-size: 1.25em;
  border-bottom: 1px solid #e5e7eb;
  padding-bottom: 0.25em;
}

.prose h3 {
  font-size: 1.125em;
}

.prose p {
  margin-bottom: 1em;
}

.prose ul,
.prose ol {
  margin-bottom: 1em;
  padding-left: 1.5em;
}

.prose li {
  margin-bottom: 0.25em;
}

.prose blockquote {
  border-left: 4px solid #3b82f6;
  padding-left: 1em;
  margin: 1em 0;
  font-style: italic;
  background-color: #f8fafc;
  padding: 0.75em 1em;
  border-radius: 0.25rem;
}

.prose table {
  width: 100%;
  border-collapse: collapse;
  margin: 1em 0;
}

.prose th,
.prose td {
  border: 1px solid #d1d5db;
  padding: 0.5em;
  text-align: left;
}

.prose th {
  background-color: #f3f4f6;
  font-weight: 600;
}

.prose code {
  background-color: #f1f5f9;
  color: #1e293b;
  padding: 0.125rem 0.375rem;
  border-radius: 0.25rem;
  font-size: 0.875em;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  border: 1px solid #e2e8f0;
}

/* 代码块包装器样式 */
.prose .code-block-wrapper {
  margin: 1em 0;
  border-radius: 0.5rem;
  overflow: hidden;
  border: 1px solid #e2e8f0;
  background-color: #f8fafc;
}

.prose .code-block-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5rem 1rem;
  background-color: #f1f5f9;
  border-bottom: 1px solid #e2e8f0;
  font-size: 0.75rem;
}

.prose .code-language {
  color: #64748b;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.05em;
}

.prose .copy-code-btn {
  display: flex;
  align-items: center;
  padding: 0.25rem 0.5rem;
  background-color: transparent;
  border: 1px solid #cbd5e1;
  border-radius: 0.25rem;
  color: #64748b;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 0.75rem;
}

.prose .copy-code-btn:hover {
  background-color: #e2e8f0;
  border-color: #94a3b8;
  color: #475569;
}

.prose .code-block-wrapper pre {
  background-color: #1e293b;
  color: #f1f5f9;
  padding: 1rem;
  margin: 0;
  overflow-x: auto;
  border-radius: 0;
  border: none;
}

.prose .code-block-wrapper pre code {
  background-color: transparent;
  color: inherit;
  padding: 0;
  border: none;
  font-size: 0.875em;
  line-height: 1.5;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
}

/* 传统pre标签样式（用于非代码块的pre） */
.prose pre:not(.code-block-wrapper pre) {
  background-color: #1e293b;
  color: #f1f5f9;
  padding: 1rem;
  border-radius: 0.5rem;
  overflow-x: auto;
  margin: 1em 0;
  border: 1px solid #334155;
  position: relative;
}

/* 代码高亮样式 */
.hljs {
  background: #1e293b !important;
  color: #f1f5f9;
}

.hljs-keyword {
  color: #7c3aed;
  font-weight: bold;
}

.hljs-string {
  color: #10b981;
}

.hljs-comment {
  color: #6b7280;
  font-style: italic;
}

.hljs-number {
  color: #f59e0b;
}

.hljs-function {
  color: #3b82f6;
}

.hljs-variable {
  color: #ef4444;
}

.hljs-tag {
  color: #8b5cf6;
}

.hljs-attr {
  color: #06b6d4;
}

.hljs-title {
  color: #f59e0b;
  font-weight: bold;
}

/* 强调样式 */
.prose strong {
  font-weight: 600;
  color: #1f2937;
}

.prose em {
  font-style: italic;
  color: #374151;
}

/* 链接样式 */
.prose a {
  color: #3b82f6;
  text-decoration: underline;
  text-decoration-color: #93c5fd;
}

.prose a:hover {
  color: #1d4ed8;
  text-decoration-color: #3b82f6;
}

/* 分隔线样式 */
.prose hr {
  border: none;
  border-top: 2px solid #e5e7eb;
  margin: 2em 0;
}

/* 代码块语言标签 */
.prose pre::before {
  content: attr(data-lang);
  position: absolute;
  top: 0.5rem;
  right: 0.75rem;
  font-size: 0.75rem;
  color: #94a3b8;
  text-transform: uppercase;
  font-weight: 500;
}
</style>